package com.zis.system.server;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zis.starter.core.Constant;
import com.zis.starter.core.ResponseEntity;
import com.zis.starter.core.SearchParams;
import com.zis.system.dao.OrgDao;
import com.zis.system.inter.IOrgInter;
import com.zis.system.model.Org;
import org.beetl.sql.core.engine.PageQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * Create by wangshen 2018/4/13
 */
@Service
@Transactional("txManager")
public class OgrInterImpl implements IOrgInter {

    @Autowired
    private OrgDao orgDao;

    @Override
    public ResponseEntity insert(Org model) throws Exception {
        int num = orgDao.getSQLManager().insert(model);
        if (num > 0) {
            return ResponseEntity.success(Constant.DATA_RESULT_SUCCEED);
        }
        return ResponseEntity.failure(Constant.DATA_RESULT_FAIL);
    }

    @Override
    public ResponseEntity update(Org model) throws Exception {
        int num = orgDao.getSQLManager().updateTemplateById(model);
        if (num > 0) {
            return ResponseEntity.success(Constant.DATA_RESULT_SUCCEED);
        }
        return ResponseEntity.failure(Constant.DATA_RESULT_FAIL);
    }

    @Override
    public ResponseEntity delete(String id) throws Exception {
        // 判断是否存在下级
        Map<String, Object> params = new HashMap<>();
        params.put("parentId", id);
        ResponseEntity responseEntity = this.findByCondition(params);
        if (responseEntity.getCode() == 0) {
            return ResponseEntity.failure("当前机构存在下级机构，无法删除");
        }
        int num = orgDao.getSQLManager().deleteById(Org.class, id);
        if (num > 0) {
            return ResponseEntity.success(Constant.DATA_RESULT_SUCCEED);
        }
        return ResponseEntity.failure(Constant.DATA_RESULT_FAIL);
    }

    @Override
    public ResponseEntity selectById(String id) throws Exception {
        return null;
    }

    @Override
    public PageQuery<Org> findByPage(SearchParams params) throws Exception {
        PageQuery<Org> query = new PageQuery<>();
        query.setPageNumber(params.getPage());
        query.setPageSize(params.getPageSize());
        query.setParas(params.getParams());
        orgDao.getSQLManager().pageQuery("system.org.query", Org.class, query);
        return query;
    }

    @Override
    public ResponseEntity findByCondition(Map params) throws Exception {
        List<Org> resultList = orgDao.getSQLManager().select("system.org.query", Org.class, params);
        if (resultList != null && resultList.size() > 0) {
            return ResponseEntity.success(JSON.parseArray(JSON.toJSONString(resultList)));
        }
        return ResponseEntity.failure(Constant.DATA_RESULT_NULL);
    }

    /**
     * 查询全部转为tree
     * @return
     * @throws Exception
     */
    @Override
    public ResponseEntity findAllConvertTree() throws Exception {
        JSONArray orgTree = new JSONArray();
        // 查询一级菜单
        List<Org> rootList = orgDao.findByParentId(null);
        if (rootList != null && rootList.size()>0) {
            for (Org org : rootList) {
                LinkedHashMap<String, Object> rootNode = new LinkedHashMap<>();
                rootNode.put("id", org.getOrgId());
                rootNode.put("pid", "0");
                rootNode.put("name", org.getOrgName());
                rootNode.put("idKey", org.getOrgId());
                rootNode.put("open", true);
                rootNode.put("nocheck", false);
                // 设置下级节点
                findBySubNode(org.getOrgId(), rootNode);
                orgTree.add(rootNode);
            }
            return ResponseEntity.success(orgTree);
        }
        return ResponseEntity.failure(Constant.DATA_RESULT_NULL);
    }

    /**
     * 递归获取下级节点信息
     * @param parentId
     * @return
     */
    private LinkedHashMap<String, Object> findBySubNode(String parentId, LinkedHashMap<String, Object> rootNode) {
        JSONArray orgSubTree = new JSONArray();
        List<Org> orgList = orgDao.findByParentId(parentId);
        boolean open = true;
        if (orgList != null && orgList.size() > 0) {
            for (Org org : orgList) {
                if(org.getOrgType().equals("COMM-VILLAGE_NODE")||org.getOrgType().equals("TOWN_NODE")){
                    open = false;
                }
                LinkedHashMap<String, Object> subNode = new LinkedHashMap<>();
                subNode.put("id", org.getOrgId());
                subNode.put("pid", rootNode.get("id"));
                subNode.put("name", org.getOrgName());
                subNode.put("idKey", org.getOrgId());
                List<Org> subList = orgDao.findByParentId(org.getOrgId());
                if (subList != null && subList.size() > 0) {
                    subNode.put("open", open);
                    findBySubNode(org.getOrgId(), subNode);
                }
                orgSubTree.add(subNode);
            }
            rootNode.put("children", orgSubTree);
            return rootNode;
        }
        return null;
    }
}
